<template>
	<div>
		<Row>
			<Col span="4">
			<Tree :data="areaList" class="tree-data-container" @on-select-change="onSelectChange" />
			</Col>
			<Col span="20">
			<Button type="error" icon="md-add" @click="onAdd" :disabled="selectedArea.nodeLevel !== 4">新增配置</Button>
			<div class="ivu-inline-block ivu-fr">
				<Dropdown @on-click="onChangeTableSize" trigger="click">
					<Tooltip class="ivu-ml" content="密度" placement="top">
						<i-link>
							<Icon type="md-list" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
							<DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
							<DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
						</DropdownMenu>
					</template>
				</Dropdown>
				<Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
					<i-link @click="onFullscreen">
						<Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
					</i-link>
				</Tooltip>
				<Tooltip class="ivu-ml" content="刷新" placement="top">
					<i-link @click="onRefresh">
						<Icon custom="i-icon i-icon-refresh" />
					</i-link>
				</Tooltip>
				<Dropdown trigger="click">
					<Tooltip class="ivu-ml" content="列设置" placement="top">
						<i-link>
							<Icon type="md-options" />
						</i-link>
					</Tooltip>
					<template #list>
						<DropdownMenu>
							<div class="ivu-p-8">列展示</div>
							<Divider size="small" class="ivu-mt-8 ivu-mb-8" />
							<li class="ivu-dropdown-item" v-for="item in dropdownColumns" :key="item.title"
								@click="item.show = !item.show">
								<Checkbox v-model="item.show"></Checkbox>
								<span>{{ item.title }}</span>
							</li>
						</DropdownMenu>
					</template>
				</Dropdown>
			</div>
			<Table ref="table" :columns="tableColumns" :data="list" :loading="loading" :size="tableSize" class="ivu-mt">
				<template #status="{ row }">
					<Switch :model-value="row.status" :true-value="0" :false-value="1"
						@on-change="(value) => onChangeStatus(row, value)" size="large">
						<template #open>
							<span>开启</span>
						</template>
						<template #close>
							<span>关闭</span>
						</template>
					</Switch>
				</template>
				<template #action="{ row }">
					<div @click.stop.prevent>
						<a style="color: #2d8cf0;" @click="onShowEdit(row)">编辑</a>
						<Divider type="vertical" />
						<Poptip confirm title="您确定删除该配置了吗？" transfer @on-ok="onDelete(row)">
							<a style="color: #ed4014;">删除</a>
						</Poptip>
					</div>
				</template>
			</Table>
			<div class="ivu-mt ivu-text-center">
				<Page :total="total" v-model="pageNum" show-total show-sizer show-elevator :page-size="pageSize"
					@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
			</div>
			</Col>
		</Row>
		<Modal :title="`${this.configInfo.id ? '编辑' : '新增'}配置`" v-model="visible" @on-cancel="onCancel"
			class-name="form-modal" :mask-closable="false" :width="1000">
			<Row :gutter="8">
				<Col span="24" v-if="!this.configInfo.id">
				<Divider orientation="left">选择信号</Divider>
				</Col>
				<Col span="11" v-if="!this.configInfo.id">
				<Table size="small" :columns="signalColumns" :data="filteredAllSignals"
					@on-selection-change="onCheckFromChange" />
				</Col>
				<Col span="2" v-if="!this.configInfo.id">
				<div class="arrow">
					<Icon type="md-arrow-round-forward" size="24" @click="onConfirmSelect" />
					<Icon type="md-arrow-round-back" size="24" style="margin-top: 10px;" @click="onCancelSelect" />
				</div>
				</Col>
				<Col span="11" v-if="!this.configInfo.id">
				<Table size="small" :columns="signalColumns" :data="selectedSignals" @on-selection-change="onCheckToChange" />
				</Col>
				<Col span="24" v-if="!this.configInfo.id">
				<Divider orientation="left">配置逻辑</Divider>
				</Col>
				<Col span="24">
				<Form ref="configInfo" :model="configInfo" :rules="configRules">
					<Row :gutter="16">
						<Col span="8">
						<FormItem label="监控类型" prop="alarmType">
							<Select v-model="configInfo.alarmType" placeholder="请选择监控类型">
								<Option v-for="key in Object.keys(AlarmTypes)" :value="key" :key="key">{{ AlarmTypes[key] }}
								</Option>
							</Select>
						</FormItem>
						</Col>
						<Col span="8">
						<FormItem label="告警等级" prop="alarmLevel">
							<Select v-model="configInfo.alarmLevel" placeholder="请选择告警等级">
								<Option v-for="key in Object.keys(AlarmLevels)" :value="key" :key="key">{{ AlarmLevels[key] }}
								</Option>
							</Select>
						</FormItem>
						</Col>
						<Col span="8" v-if="configInfo.alarmType === '1'">
						<FormItem label="触发逻辑" prop="comparisonLogic">
							<Select v-model="configInfo.comparisonLogic" placeholder="请选择触发逻辑">
								<Option v-for="key in Object.keys(ComparisonLogics)" :value="key" :key="key">{{ ComparisonLogics[key] }}
								</Option>
							</Select>
						</FormItem>
						</Col>
						<Col span="8" v-if="configInfo.alarmType === '1'">
						<FormItem label="告警阈值" prop="threholdValue">
							<Input v-model="configInfo.threholdValue" placeholder="请输入告警阈值" />
						</FormItem>
						</Col>
						<Col span="8" v-if="configInfo.alarmType === '1'">
						<FormItem label="解除阈值" prop="recoveryThresholdValue">
							<Input v-model="configInfo.recoveryThresholdValue" placeholder="请输入解除阈值" />
						</FormItem>
						</Col>
						<Col span="8">
						<FormItem label="延迟时间" prop="delayTime">
							<Input v-model="configInfo.delayTime" placeholder="请输入延迟时间" />
						</FormItem>
						</Col>
						<Col span="24">
						<FormItem label="告警内容" prop="alarmContent">
							<Input v-model="configInfo.alarmContent" placeholder="请输入告警内容" />
						</FormItem>
						</Col>
					</Row>
				</Form>
				</Col>
			</Row>
			<template #footer>
				<Button type="text" @click="onCancel">取消</Button>
				<Button type="primary" @click="onConfirm" :loading="loading">确定</Button>
			</template>
		</Modal>
	</div>
</template>
<script>
import { cloneDeep } from 'lodash'
import { getAreaList } from '@/api/common'
import { getDeviceSignal } from '@api/alarm'
import { getAlarmStrategies, createAlarmStrategy, updateAlarmStrategy } from '@api/alarm'

export default {
	data() {
		return {
			AlarmTypes: {
				1: '数据异常',
				2: '状态异常',
			},
			AlarmLevels: {
				1: '紧急',
				2: '严重',
				3: '警告',
				4: '消息',
			},
			ComparisonLogics: {
				'>': '>',
				'<': '<',
				'=': '=',
				'>=': '>=',
				'<=': '<='
			},
			loading: false,
			list: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			tableSize: 'small',
			tableFullscreen: false,
			allSignals: [],
			visible: false,
			areaData: [],
			areaList: [],
			selectedArea: {},
			selectingSignals: [],
			selectedSignals: [],
			configInfo: {
				id: '',
				alarmType: '',
				alarmLevel: '',
				comparisonLogic: '',
				threholdValue: '',
				recoveryThresholdValue: '',
				delayTime: '',
				alarmContent: ''
			},
			configRules: {}
		}
	},
	computed: {
		columns() {
			return [
				{ title: '监控设备', key: 'deviceName' },
				{ title: '监控信号', key: 'signalName' },
				{ title: '监控类型', key: 'alarmTypeName' },
				{ title: '触发条件', key: 'comparisonLogicName' },
				{ title: '报警等级', key: 'alarmLevelName' },
				{ title: '报警周期', key: 'alarmPeriod' },
				{ title: '状态', key: 'status', slot: 'status' },
				{ title: '操作', key: 'action', slot: 'action', align: 'center', width: 120, fixed: 'right' }
			]
		},
		tableColumns() {
			const columns = [...this.columns];
			return columns
		},
		dropdownColumns() {
			return this.columns.filter(item => item.title)
		},
		signalColumns() {
			return [
				{ type: 'selection', align: 'center', width: 60 },
				{ title: '设备名称', key: 'deviceName' },
				{ title: '信号名称', key: 'signalName' },
			]
		},
		filteredAllSignals() {
			return this.allSignals.filter(item => {
				return !this.selectedSignals.map(i => i.id).includes(item.id)
			})
		}
	},
	async mounted() {
		const response = await getAreaList({})
		this.areaData = response
		this.onGenerateTree(response)
	},
	methods: {
		async getAllSignals() {
			const response = await getDeviceSignal({
				roomId: this.selectedArea.nodeId
			})
			this.allSignals = response || []
		},
		async getData() {
			if (this.loading) return;
			this.loading = true;
			const params = this.$parent.$parent.$refs.form.data;
			const response = await getAlarmStrategies({
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				keyword: params.keyword || undefined
			})
			this.list = (response.records || []).map(item => ({
				...item,
				alarmTypeName: this.AlarmTypes[item.alarmType],
				alarmLevelName: this.AlarmLevels[item.alarmLevel],
				comparisonLogicName: `${item.comparisonLogic}${item.threholdValue}`
			}))
			this.total = response.total;
			this.loading = false;
		},
		onGenerateTree(areaList) {
			const treeData = areaList.filter(area => !area.parentId)
			for (let i = 0; i < treeData.length; i++) {
				treeData[i].expand = true
				treeData[i].children = []
				treeData[i].render = (h, { root, node, data }) => {
					return h('span', {}, data.nodeName)
				}
				cloneDeep(areaList).forEach(area => {
					if (area.parentId === treeData[i].nodeId) {
						if (!area.children) {
							area.expand = true
							area.children = []
							cloneDeep(areaList).forEach(subArea => {
								if (subArea.parentId === area.nodeId) {
									subArea.expand = true
									subArea.children = []
									cloneDeep(areaList).forEach(thirdArea => {
										if (thirdArea.parentId === subArea.id) {
											thirdArea.expand = true
											thirdArea.children = []
											thirdArea.render = (h, { root, node, data }) => {
												return h('span', {
													style: {
														width: '100%'
													}
												}, [
													h('span', {
														style: {
															display: 'inline-block',
															width: '80px',
														}
													}, data.nodeName),
												]);
											}
											subArea.children.push(thirdArea)
										}
									})
									subArea.render = (h, { root, node, data }) => {
										return h('span', {
											style: {
												width: '100%'
											}
										}, [
											h('span', {
												style: {
													display: 'inline-block',
													width: '80px',
												}
											}, data.nodeName),
										]);
									}
									area.children.push(subArea)
								}
							})
						}
						area.render = (h, { root, node, data }) => {
							return h('span', {
								style: {
									width: '100%'
								}
							}, [
								h('span', {
									style: {
										display: 'inline-block',
										width: '80px',
									}
								}, data.nodeName),
							]);
						}
						areaList[i].children.push(area)
					}
				})
			}
			this.areaList = treeData
		},
		onSelectChange(_, selectedArea) {
			this.selectedArea = selectedArea
			this.getData()
		},
		onChangeTableSize(size) {
			this.tableSize = size;
		},
		onFullscreen() {
			this.tableFullscreen = !this.tableFullscreen;
			this.$emit('on-fullscreen', this.tableFullscreen);
		},
		onRefresh() {
			this.getData();
		},
		onChangePage(page) {
			this.pageNum = page;
			this.getData();
		},
		onChangePageSize(size) {
			this.pageNum = 1;
			this.pageSize = size;
			this.getData();
		},
		onSearch() {
			this.pageNum = 1;
			this.getData();
		},
		onAdd() {
			this.getAllSignals()
			this.configInfo.id = undefined
			this.visible = true
		},
		onShowEdit(row) {
			this.configInfo = {
				id: row.id,
				alarmType: `${row.alarmType}`,
				alarmLevel: `${row.alarmLevel}`,
				comparisonLogic: `${row.comparisonLogic}`,
				threholdValue: `${row.threholdValue}`,
				recoveryThresholdValue: `${row.recoveryThresholdValue}`,
				delayTime: `${row.delayTime}`,
				alarmContent: `${row.alarmContent}`
			}
			this.visible = true
		},
		onCheckFromChange(selection) {
			this.selectingSignals = selection
		},
		onCheckToChange(selection) {
			this.selectingSignals = selection
		},
		onConfirmSelect() {
			this.selectedSignals = [
				...this.selectedSignals,
				...this.selectingSignals
			]
			this.selectingSignals = []
		},
		onCancelSelect() {
			this.selectedSignals = this.selectedSignals.filter(item => {
				return !this.selectingSignals.map(i => i.id).includes(item.id)
			})
			this.selectingSignals = []
		},
		onCancel() {
			this.selectedSignals = []
			this.selectingSignals = []
			this.visible = false
		},
		async onConfirm() {
			const params = {
				...this.configInfo,
			}
			if (!params.id) {
				params.deviceId = this.selectedSignals[0].deviceId
				params.deviceName = this.selectedSignals[0].deviceName
				params.signalId = this.selectedSignals[0].signalId
				params.signalName = this.selectedSignals[0].signalName
			}
			const response = !params.id ? await createAlarmStrategy(params) : await updateAlarmStrategy(params)
			if (response.code === 1000) {
				this.onCancel()
				this.onSearch()
			}
		},
		async onChangeStatus(row, value) {
			await updateAlarmStrategy({
				id: row.id,
				status: value
			})
		},
		async onDelete(row) {
			const response = await updateAlarmStrategy({
				id: row.id,
				isDelete: 1
			})
			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.pageNum = 1
				this.getData()
			}
		}
	}
}
</script>
<style lang="less">
.form-modal {
	.ivu-form-item-label {
		width: 100%;
		text-align: left;
	}

	.ivu-date-picker {
		width: 100%;
	}

	.arrow {
		width: 100%;
		height: 100%;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
}
</style>
